package com.bt7274.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Data 2025/5/25
 * @Version 1.0
 * @Description 会话工具类，用于获取当前登录用户信息
 */
public class SessionUtils {

    /**
     * 获取当前登录用户ID
     * @return 用户ID，如未登录则返回null
     */
    public static String getCurrentUserId() {
        HttpSession session = getSession();
        return session != null ? (String) session.getAttribute("userId") : null;
    }

    /**
     * 获取当前登录用户名
     * @return 用户名，如未登录则返回null
     */
    public static String getCurrentUsername() {
        HttpSession session = getSession();
        return session != null ? (String) session.getAttribute("username") : null;
    }

    /**
     * 获取当前用户权限组
     * @return 权限组ID，如未登录则返回null
     */
    public static Integer getCurrentPermissionGroup() {
        HttpSession session = getSession();
        return session != null ? (Integer) session.getAttribute("permissionGroup") : null;
    }

    /**
     * 检查当前用户是否已登录
     * @return 是否已登录
     */
    public static boolean isUserLoggedIn() {
        return getCurrentUserId() != null;
    }

    /**
     * 获取当前请求的Session
     * @return HttpSession对象，如不存在则返回null
     */
    private static HttpSession getSession() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null;
        }

        HttpServletRequest request = attributes.getRequest();
        return request.getSession(false);
    }
}